local ESCHSTAT=require'zdc.typetsk'.ESCHSTAT
local tskdo=require'zsvc.tskdo'
module(..., package.seeall)

local SchDisp = {}
local SchDisp_mt = {__metatable = {}, __index = SchDisp}

function MakeInhMT(ch)
	ch=ch or {}
	for _i,_j in pairs(SchDisp) do
		ch[_i]=_j
	end
	return ch
end

function new(dal,cfg, logger,childmt)
	local obj=setmetatable({dal=dal,cfg=cfg,logger=logger or zdc.logger.defaultlog}, childmt or SchDisp_mt)
	return obj
end

function SchDisp:SpawnTask(tskid,taskdef)
	local ok,sid,msg=self.dal:CallNode(nil,self.tskid,'AddResult',{ts=taskdef.ts_next})
	if not ok or not sid then
		print(tskid,sid or msg)
		return
	end
	local tsk=tskdo.new(self.dal,tskid..'/'..sid,taskdef)
	local ok,msg=xpcall(function ()
		tsk:dotask()
	end,debug.traceback)
	if not ok then
		print(tskid,msg)
	end
end

function SchDisp:poll(maxcnt)
	local ok,r,msg=self.dal:CallNode(user,self.cfg.cornid,'CalcSchedule',{})
	if not ok then return nil,r end
	if not r then return nil,msg end
	local ts=os.time()
	local cnt=0
	for k,v in ipairs(r) do
		local def=v.taskdef
		if def.stat==ESCHSTAT.queue and def.ts_next<=ts then
			self:SpawnTask(v.tskid,def)
			cnt=cnt+1
		end
	end
	return cnt
end
